<template>
  <div :class="['!w-[var(--left-tree-max-width)] px-0px tree-min-width']">
    <div class="flex justify-center items-center pl-0px mt-20px">
      <el-select
        v-model="currentDepartment"
        clearable
        placeholder="请选择根节点"
        @change="handleProductChange"
        style="width: 240px"
      >
        <el-option
          v-for="item in departmentOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <ElDivider />
    <div class="items-center pl-20px mt-20px">
      <div class="flex-1 mb-15px">型号设备树</div>
      <ElInput
        v-model="currentchlDepartment"
        class="flex-[2]"
        placeholder="搜索设备型号"
      />
    </div>
    <div class="h-[calc(100%-80px)] overflow-y pl-15px mt-15px">
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
         :show-checkbox="showCheckbox"
        :expand-on-click-node="false"
        node-key="deviceCode"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'deviceName',
          children: 'children'

        }"
        :filter-node-method="filterNode"
        @current-change="handleCurrentChange"
      >
        <template #default="{ data }">
          <div
            :title="data.deviceName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.deviceName }}
          </div>
        </template>
      </ElTree>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, defineProps, defineEmits, nextTick } from 'vue'
import { ElTree, ElInput, ElDivider, ElMessage } from "element-plus";
import type { DepartmentItem } from "@/components/DepartmentTree/types";
// import { useDeviceTreeStore } from '@/store/modules/deviceTreeStore1'

// 定义Props
const props = defineProps({
  // 可以添加需要的props
  showCheckbox: {
    type: Boolean,
    default: false,
  },
})

// 定义Emits
const emit = defineEmits(['current-change', 'department-change'])

// 使用Pinia store


const currentchlDepartment = ref(""); // 搜索关键词
const departmentOptions = ref<{ label: string; value: string }[]>([]);
const currentDepartment = ref()
const currentNodeKey = ref()
const treeEl = ref<InstanceType<typeof ElTree>>();
const departmentList = ref<DepartmentItem[]>([]);



// 获取根节点
const getRootDepartment = async () => {
  try {
    const res = await "/dDeviceCatalog/rootList".get();
    departmentOptions.value = res.data.map((item) => ({
      label: item.deviceName,
      value: item.deviceCode,
    }));
if (departmentOptions.value.length > 0) {
      currentDepartment.value = departmentOptions.value[0].value;
    }


    if (currentDepartment.value) {
      await getTree(currentDepartment.value);
    }
  } catch (error) {
    console.error("获取根节点失败:", error);
  }
};

// 获取树
const getTree = async (rootCode: string) => {
  try {
    // console.log("请求参数:", { parentCode: rootCode });
    const res = await "/dDeviceCatalog/tree".get({ parentCode: rootCode });

    departmentList.value = [res.data] || [];

    // 等待DOM更新
    await nextTick();
selectFirstNode();
    // 树加载完成后，尝试恢复选中的节点或选中第一个节点
    // if (deviceTreeStore.currentNodeKey) {
    //   // 如果store中有保存的选中节点，恢复它
    //   treeEl.value?.setCurrentKey(deviceTreeStore.currentNodeKey);
    // } else {
    //   // 选中第一个节点
    //   selectFirstNode();
    // }
  } catch (error) {
    console.error("获取树数据失败:", error);
    departmentList.value = [];
  }
};

// 选中第一个节点
const selectFirstNode = () => {
  if (departmentList.value.length > 0) {
    const firstNode = findFirstNode(departmentList.value[0]);
    if (firstNode) {
      // 设置当前节点key
      currentNodeKey.value = firstNode.deviceCode;
      // 设置树选中
      treeEl.value?.setCurrentKey(firstNode.deviceCode);
      // 触发current-change事件，确保表单数据更新
      handleCurrentChange(firstNode);
    }
  }
};

// 辅助函数：查找树中的第一个节点
const findFirstNode = (node: DepartmentItem): DepartmentItem => {
  if (!node) return null;
  // 返回当前节点
  return node;
};

// 产品切换
const handleProductChange = async (value: string) => {

  currentDepartment.value = value;
  // deviceTreeStore.setCurrentDepartment(value);
  // // 清空当前选中节点
  // deviceTreeStore.setCurrentNode(null);
  currentNodeKey.value = '';
  await getTree(value);
  emit('department-change', value);
};

const filterNode = (value: string, data: DepartmentItem) => {
  if (!value) return true;
  return data.deviceName.includes(value);
};
const getCheckedNodes = async () => {
  return treeEl.value?.getCheckedNodes(false,true) || [];
}
// 当前节点变化
const handleCurrentChange = (data: DepartmentItem) => {

  if (data) {
    // 保存到store
    // deviceTreeStore.setCurrentNode(data);
    currentNodeKey.value = data.deviceCode;

    // 触发事件
    emit('current-change', data);
  }
};

// 监听搜索关键词变化
watch(
  () => currentchlDepartment.value,
  (val) => {
    treeEl.value!.filter(val);
  }
);

// 暴露方法供父组件调用
defineExpose({
  refreshTree:  () => {
    if (currentDepartment.value) {
      getTree(currentDepartment.value);
    } else {
      getRootDepartment();
    }
  },
  getCheckedNodes,
  setCurrentKey: (key: string) => treeEl.value?.setCurrentKey(key),
  getTreeData: () => departmentList.value
})

onMounted(() => {
  getRootDepartment();
});
</script>

<style scoped lang="less">
.tree-min-width {
  min-width: 200px !important;
}

:deep(.el-tree-node__content) {
  height: 40px !important;
}

:deep(.is-current-node .el-tree-node .el-tree-node__content) {
  background-color: transparent !important;
  color: inherit !important;
  font-weight: normal;
}
:deep(.is-current-node > .el-tree-node__content) {
  background-color: var(--el-color-primary) !important;
  border-radius: 0 20px 20px 0;
  color: var(--el-tree-content-color) !important;
  font-weight: bold;
}

:deep(.el-tree) {
  background: transparent !important;
}

:deep(.el-card) {
  --el-card-bg-color: transparent !important;
  background-color: transparent !important;
}
</style>
